package com.tensquare.user.service;


import com.tensquare.user.dao.AdminDao;
import com.tensquare.user.pojo.Admin;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;

@Service
@Transactional
public class AdminService {

    @Autowired
    private AdminDao adminDao;

    @Autowired
    private BCryptPasswordEncoder encoder;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private HttpServletRequest request;

    public  void  add(Admin admin){
        admin.setPassword(encoder.encode(admin.getPassword()));
        adminDao.save(admin);

    }

    public Admin login(Admin admin) {
        //先根据用户
        Admin loginname = adminDao.findByLoginname(admin.getLoginname());
        //然后拿数据库中的密码和用户输入的密码匹配是否相同
        if(loginname!=null&&encoder.matches(admin.getPassword(),loginname.getPassword())){
            return loginname;
        }
        return null;
    }

    public void delete(String id) {
        String header=request.getHeader("Authorization");
        if(StringUtils.isNotBlank(header)){
            throw new RuntimeException("权限不足");
        }
        if(!header.startsWith("Bearer ")){

            throw new RuntimeException("权限不足");
        }
        //得到token
        String token = header.substring(7);
        try{
            Claims claims = jwtUtil.parseJWT(token);
            String role = (String) claims.get("role");
            if(role==null||!role.equals("admin")){
                throw new RuntimeException("权限不足");
            }

        }catch (Exception e){
            throw new RuntimeException("权限不足");

        }

        adminDao.deleteById(id);
    }
}
